package gui;

import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.Calculator;
import model.Pharser;
import data.Parameter;
import data.Project;

public class Gui extends JFrame {
	class ComputeButton extends JButton implements ActionListener {
		
		public ComputeButton() {
			super("Compute");
			this.addActionListener(this);
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			calculate();
		}
		
	}
	class openFileButton extends JButton implements ActionListener {
		
		public openFileButton() {
			super("Choose database");
			this.addActionListener(this);
		}

		@Override
		public void actionPerformed(ActionEvent arg0) {
			//Handle open button action.
	            int returnVal = fc.showOpenDialog(getParent());
	 
	            if (returnVal == JFileChooser.APPROVE_OPTION) {
	                File file = fc.getSelectedFile();
	                //This is where a real application would open the file.
	                filePath = file.getAbsolutePath();
	                //System.out.println(filePath);
	            }
		}
	}
	JPanel pane;
	JButton button;
	public JFileChooser fc;
	public static String filePath;
	JLabel answer = new JLabel("...");
	Map<String, JComboBox> fields = new HashMap<String, JComboBox>();
	JTextField[] doubleFields = new JTextField[2];
	private String sim = "Similarity Threshold: ";
	Calculator calc;
	
	private boolean errorOcurred = false;

	public Gui() {
		super("Effort Estimation");
		this.setBounds(new Rectangle(800, 500));
		pane = new JPanel(new GridLayout(20, 2));
		setContentPane(pane);

		for (int i=0; i < Pharser.fnames.length-1; i++){//String name: Pharser.fnames) {
			if(i<15)
			{
				String name = Pharser.fnames[i];
				pane.add(new JLabel(name));
				fields.put(name, setupDropDownMenu());
			}else
			{
				String name = Pharser.fnames[i];
				pane.add(new JLabel(name));
				JTextField tf =new JTextField("10");
				pane.add(tf);
				doubleFields[i-15] =tf;
			}
		}
		pane.add(new JLabel(sim));
		JTextField tf = new JTextField("0.4");
		pane.add(tf);
		doubleFields[1]=tf;
		button = new ComputeButton();
		pane.add(button);
		pane.add(answer);
		
		//File open button
		fc = new JFileChooser();
		JButton openButton = new openFileButton();
		pane.add(openButton);
		//
		
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		validate();
		setVisible(true);
		
		filePath = "src/testdata.txt";
	}
	
	public void calculate() {
		Project p = new Project();
		
		for (Entry<String, JComboBox> e: fields.entrySet()) {
			
			if (!e.getValue().getSelectedItem().toString().equals("Option disabled")){
//				e.getKey().compareTo("Project Size") != 0 && 
//					e.getKey().compareTo("Actual effort(months)") != 0) { // is double field		
				Parameter par = new Parameter(e.getKey(),e.getValue().getSelectedItem().toString());
				p.params.put(e.getKey(), par);
			} 
		}
		double threshold =0.4;
		for (int i=0; i < 2; i++) {
			double tmp=0;
			try{
				tmp = Double.parseDouble( doubleFields[i].getText());
			}
			catch(NumberFormatException f){
				doubleFields[i].setText("Wrong Input! Should be numerical.");
				errorOcurred = true;
			}
			if(i==0){
				p.params.put(Pharser.fnames[Pharser.fnames.length-2],new Parameter(tmp));
			}
			else{
				if(tmp >1|| tmp<0){
					doubleFields[i].setText("Wrong Input! Should be between 0 and 1.");
					errorOcurred = true;
				}
				threshold = tmp;
			}	
		}
	
		double effort;
		if (calc != null&&!errorOcurred) {
			Pharser pars = new Pharser(filePath);
			List<Project> db = pars.projects();
			
			effort = calc.calculate(p, db, threshold);
			if(effort<0)
				answer.setText("Similarity for the projects in database was below threshold!");
			else{
				int effort_hours = (int) (effort%24);
				int effort_days = (int) ((effort/24)%30.4368);
				int effort_months = (int) (effort/(24*30.4368)%12);
				int effort_years = (int) (effort/(24*30.4368*12)%12);
				answer.setText("Effort Estimate: "+effort_years+" years " +effort_months+ " months " +effort_days+ " days " +effort_hours+ " hours");
			}
		} else {
			answer.setText("An error occured\n");
			
		}
		errorOcurred = false;//reset
	}

	public void setCalculator(Calculator c) {
		calc = c;
	}
	
	private JComboBox setupDropDownMenu() {
		String[] optStrings = { "Option disabled", "Very_Low", "Low", "Nominal", "High", "Very_High", "Extra_High" };
		//Create the combo box, select item at index 0.
		JComboBox optList = new JComboBox(optStrings);
		optList.setSelectedIndex(0);
		pane.add(optList);
		//optList.addActionListener(this); //Fungerar inte pga v�r design, men beh�vs det???
		return optList;
	}
}